package com.jfinal.config;

import com.jfinal.kit.Prop;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;


/**
 * @author CHEN
 */
public abstract class ConfigKit {

    public static final String DEFAULT_CONFIG_NAME = "main";
    
    public static String createPrefix(String pluginName, String configName) {
        String prefix = pluginName;
        if (!DEFAULT_CONFIG_NAME.equals(configName)) {
            prefix += "." + configName;
        }
        return prefix;
    }

    public static List<String> findConfigNames(List<String> propNames, String suffix) {
        List<String> configNames = new ArrayList<>();
        List<String> propNameList = findByEndsWith(propNames, suffix);
        for (String propName : propNameList) {
            String[] arr = propName.split("\\.");
            if (arr.length == 2) {
                configNames.add(DEFAULT_CONFIG_NAME);
            } else {
                configNames.add(arr[1]);
            }
        }
        return configNames;
    }


    public static List<String> findByEndsWith(List<String> strings, String suffix) {
        return strings.stream()
                .filter(str -> str.endsWith(suffix))
                .collect(Collectors.toList());
    }

    public static List<String> findConfigNames(Prop prop, String pluginName, String suffix) {
        List<String> propNames = findPropNames(prop.getProperties(), pluginName + ".");
        return findConfigNames(propNames, suffix);
    }

    public static List<String> findPropNames(Properties properties, String prefix) {
        List<String> result = new ArrayList<>();
        Enumeration enu = properties.keys();
        while (enu.hasMoreElements()) {
            String key = (String) enu.nextElement();
            if (key.startsWith(prefix)) {
                result.add(key);
            }
        }
        return result;
    }


}
